import axios from 'axios';
import {Base64} from 'js-base64'

///////// axios实例 /////////
const native = axios.create({
    //baseURL: process.env.VUE_APP_BASE_API, // api的base_url
    timeout: 3000 // 请求超时时间
});

const http = axios.create({
    //baseURL: process.env.VUE_APP_BASE_API, // api的base_url
    timeout: 3000 // 请求超时时间
});

// 请求拦截器
http.interceptors.request.use(
    async config => {
        console.log('axios request:', config);
        let original = config.url;
        let parser = parseURL(original);
        let url = parser.protocol + '://' +parser.host + ':'+parser.port;
        let auth = {name:'root',password:'123456'}
        // if(original.includes('/health')){
        //     return config;
        // }
        // 判定是否开启权限校验, 如果开启, 则补全 authorization 请求头信息
        let etcdAuthEnabled = false;
        let etcdToken= await native.post(url+'/v3/auth/authenticate', auth)
            .then(res=>{
                etcdAuthEnabled = true;
                return res.data.token;
            })
            .catch(error=>{
                let notEnabled = 'authentication is not enabled';
                let message = error.response.data.message;
                if(message.includes(notEnabled)){
                    etcdAuthEnabled = false;
                    return null;
                }
                throw error;
            });
        console.log('etcdToken',etcdToken);
        if(etcdAuthEnabled){
            config.headers.Authorization = etcdToken;
        }
        return config;
    },
    error => {
        // 请求错误处理
        return Promise.reject(error);
    }
);

// 响应拦截器
http.interceptors.response.use(
    response => {
        // 对响应数据做处理，例如只返回data部分
        console.log("axios response:",response)
        const code = response.status;
        // 如果返回的状态码为200，说明成功，可以直接返回数据
        if (isHttpSuccessful(code)) {
            return response;
        } else {
            // 其他状态码都当作错误处理
            return Promise.reject(response || 'error');
        }
    },
    error => {
        // 服务器状态码不为200时的错误处理
        return Promise.reject(error);
    }
);

function isHttpSuccessful(status) {
    return status >= 200 && status < 300;
}

function parseURL(url) {
    const regex = /^(https?):\/\/([^:/?]+)(?::(\d+))?([^?#]+)?(\?[^#]+)?(#.+)?$/;
    const match = url.match(regex);
    if (!match) return null;
    const [, protocol, host, port, path, query, fragment] = match;
    const parsedURL = {
        protocol: protocol,
        host: host,
        port: port ? parseInt(port) : null,
        path: path || null,
        query: query ? query.slice(1) : null,
        fragment: fragment ? fragment.slice(1) : null
    };
    return parsedURL;
}

///////// etcd 执行方法 /////////
export function health_etcd(url) {
    return http.get(url+'/health');
}

export function version_etcd(url) {
    return http.get(url+'/version');
}

// v3
export function kv_range(url,data) {
    return http.post(url+'/v3/kv/range',data);
}

// v3
export function kv_put(url,data) {
    return http.post(url+'/v3/kv/put',data);
}

// v3
export function kv_delete(url,key) {
    return http.post(url+'/v3/kv/deleterange',{"key":Base64.encode(key)});
}

export function lease_leases(url){
    return http.post(url+'/v3/lease/leases',{});
}

export function lease_grant(url,data){
    return http.post(url+'/v3/lease/grant',data);
}


export function lease_ttl(url,id){
    return http.post(url+'/v3/lease/timetolive', {"ID":id,"keys": true});
}

// v3
export function auth_user_list(url) {
    return http.post(url+'/v3/auth/user/list', {});
}

export function auth_user_add(url,data) {
    return http.post(url+'/v3/auth/user/add', data);
}

export function auth_user_get(url,name) {
    return http.post(url+'/v3/auth/user/get', {"name":name});
}

export function auth_user_delete(url,name) {
    return http.post(url+'/v3/auth/user/delete',{"name":name});
}

// v3
export function auth_role_list(url) {
    return http.post(url+'/v3/auth/role/list');
}

export function auth_role_add(url,data) {
    return http.post(url+'/v3/auth/role/add',data);
}

export function auth_role_delete(url,name) {
    return http.post(url+'/v3/auth/role/delete',{"role":name});
}

export function auth_role_get(url,name) {
    return http.post(url+'/v3/auth/role/get',{"role":name});
}

export function auth_role_grant(url,data) {
    return http.post(url+'/v3/auth/role/grant',data);
}

export function auth_authenticate(url,auth){
    // 如果没有开启, 异常 etcdserver: authentication is not enabled
    // 如果已经开启, 则正常调用; 鉴权失败 etcdserver: authentication failed, invalid user ID or password
    // 多次请求, 旧 Token 仍然可用
    return http.post(url+'/v3/auth/authenticate', auth);
}

export function auth_enable(url,token=null){
    // 如果已经开启 Auth, 没有 token 再次调用则报错 'etcdserver: user name is empty';
    // 如果没有开启 Auth, 则默认开启
    return http.post(url+'/v3/auth/enable', {});
}

export function auth_disable(url,token=null){
    return http.post(url+'/v3/auth/disable', {});
}

export function auth_user_grant(url,grant={"role":"<string>","user":"<string>"},token){
    return http.post(url+'/v3/auth/user/grant', grant);
}

// v3
export function membersEtcd(url) {
    return http.post(url+'/v3/cluster/member/list', {"linearizable": true});
}

// v3
export function leaderEtcd(url) {
    return http.post(url+'/v3/maintenance/status');
}

export function selfEtcd(url) {
    return http.get(url+'/v3/stats/self', {headers:headers});
}

export function storeEtcd(url) {
    return http.get(url+'/v3/stats/store', {headers:headers});
}

export function shiftLastChar(str) {
    if (str.length === 0) {
        return str;
    }
    let lastChar = str[str.length - 1];
    let lastCharAscii = lastChar.charCodeAt(0);
    let shiftedAscii = lastCharAscii + 1;
    let shiftedChar = String.fromCharCode(shiftedAscii);
    return str.slice(0, str.length - 1) + shiftedChar;
}


